<!-- gitee上开源的人类行为验证 -->
<template>
  <div
    class="fixed top-[20%] left-[50%] translate-x-[-50%] w-[340px] h-[270px] text-sm bg-white dark:bg-zinc-800 rounded border border-zinc-200 dark:border-zinc-900 shadow-2xl"
  >
    <!-- 验证的头部 -->
    <div class="flex items-center h-5 text-left px-1 mb-1">
      <span class="flex-grow dark:text-zinc-200">请完成安全验证</span>
      <m-svg-icon
        name="refresh"
        fillClass="fill-zinc-900 dark:fill-zinc-200"
        class="w-2.5 h-2.5 rounded-sm duration-300 hover:bg-zinc-200 dark:hover:bg-zinc-900"
        @click="onReset"
      ></m-svg-icon>
      <m-svg-icon
        name="close"
        fillClass="fill-zinc-900 dark:fill-zinc-200"
        class="w-2.5 h-2.5 ml-2 rounded-sm duration-300 hover:bg-zinc-200 dark:hover:bg-zinc-900"
        @click="onClose"
      ></m-svg-icon>
    </div>
    <!-- 验证的captcha  包来实现 -->
    <div id="captcha"></div>
  </div>
</template>

<script>
const EMIT_CLOSE = 'close'
const EMIT_SUCCESS = 'success'
</script>

<script setup>
import '@/vendor/SliderCaptcha/longbow.slidercaptcha.min.js'
import '@/vendor/SliderCaptcha/slidercaptcha.min.css'
import { onMounted, ref } from '@vue/runtime-core'
import { getCaptcha } from '@/api/system'

const emits = defineEmits([EMIT_CLOSE, EMIT_SUCCESS])

/**
 * 使用人类行为验证
 * 1.创建captcha实例
 */
onMounted(() => {
  // 生成sliderCaptcha实例
  produceCaptcha()
})
// 生成captua实例
const captcha = ref(null)
const produceCaptcha = () => {
  captcha.value = sliderCaptcha({
    id: 'captcha',
    // 拼图成功后的回调
    async onSuccess(arr) {
      const res = await getCaptcha({
        behavior: arr
      })
      if (res) {
        // 验证通过
        emits(EMIT_SUCCESS)
      }
    },
    // 拼图失败后的回调
    onFail() {
      console.log('失败了')
    },
    // 默认的验证方法
    verify() {
      return true
    }
  })
}
// 刷新
const onReset = () => {
  captcha.value.reset()
}
// 关闭
const onClose = () => {
  emits(EMIT_CLOSE)
}
</script>
<style lang="scss" scoped></style>
